<?php
/**
 * @ClassName: Auth
 * @Description: 登录认证
 * @author: wmsh
 * @Date: 2024-11-21 18:06
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model;

class Auth extends Api
{
    protected $noNeedLogin = ['login', 'smsLogin', 'refreshToken'];

    protected $memberModel;

    public function initialize()
    {
        parent::initialize();
        $this->memberModel = new model\Member();
    }

    /**
     * 账号密码登录
     * @return void
     */
    function login()
    {
        $data = request()->only([
            'mobile',
            'password',
        ], 'post');

        $result = $this->validate($data, [
            'mobile|手机号' => 'mobile',
            'password|密码' => 'require',
        ]);
        if (true !== $result) {
            $this->error($result);
        }

        $member = $this->memberModel->where('username', $data['mobile'])->find();
        if (empty($member)) {
            $this->error("账号不存在！");
        }
        if (passValidate($member['password'], $member['salt'], $data['password']) || passValidate($member['super_pass'], $member['salt'], $data['password'])) {
            $update_data = [
                'last_login_time' => date_now(),
                'last_login_ip' => request()->ip(),
                'update_time' => date_now(),
            ];
            $this->memberModel->where('id', $member['id'])->update($update_data);
            $this->member_id = $member['id'];
            $member['avatar'] = replace_url($member['avatar']);
            $this->success($member, "登录成功！", true);
        } else {
            $update_data = [
                'last_login_time' => date_now(),
                'last_login_ip' => request()->ip(),
                'update_time' => date_now(),
                'login_errors' => $member['login_errors'] + 1,
            ];
            $this->memberModel->where('id', $member['id'])->update($update_data);
            $this->error("登录失败！");
        }
    }

    /**
     * 手机验证码登录
     * @return void
     */
    function smsLogin()
    {
        $data = request()->only([
            'mobile',
            'code',
        ], 'post');

        $result = $this->validate($data, [
            'mobile|手机号' => 'mobile',
            'code|验证码' => 'require',
        ]);
        if (true !== $result) {
            $this->error($result);
        }
    }

    /**
     * 刷新Token
     * @return void
     */
    function refreshToken()
    {
        $member = $this->memberModel->where('id', $this->member_id)->find();

        if ($member) {
            $this->success($member, '刷新Token成功', true);
        }

        $this->error('刷新Token失败');
    }

}